<?php
namespace app\admin\controller;

use think\facade\Config;
use think\Controller;
use think\Db;
use think\captcha;
use think\facade\Cookie;
/**
 * 后台登录
 * Class Login
 * @package app\admin\controller
 */
class Login extends Controller
{
    /**
     * 后台登录
     * @return mixed
     */
    public function index()
    {
        return $this->fetch();
    }


    public function login()
    {
        if ($this->request->isPost()) {
            $data            = $this->request->only(['username', 'password', 'verify']);
            if (!captcha_check($data['verify'])) {
                $this->error('验证码错误');
            } else {
                $where['username'] = $data['username'];
                $where['password'] = md5($data['password'] . Config::get('salt'));
                $admin_user = Db::name('admin_user')->field('id,username,status')->where($where)->find();
                if (!empty($admin_user)) {
						Cookie::set('admin_id',$admin_user['id'],['expire'=>3600*2]);
						Cookie::set('admin_name',$admin_user['username'],['expire'=>3600*2]);
                        Db::name('admin_user')->update(
                            [
                                'last_login_time' => date('Y-m-d H:i:s', time()),
                                'last_login_ip'   => $this->request->ip(),
                                'id'              => $admin_user['id']
                            ]
                        );
                    $this->success('登录成功', 'admin/index/index');
                } else {
                    $this->error('用户名或密码错误');
                }
            }
        }
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        //Session::delete('admin_id');
        //Session::delete('admin_name');
        Cookie::delete('admin_id');
        Cookie::delete('admin_name');
        $this->success('退出成功', 'admin/login/index');
    }
}
